package com.util.spliterator;

import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Description
 * @Author away
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2019/11/4
 */
public class NumCounter {
    private int num;
    private int sum;
    // 是否当前是个完整的数字
    private boolean isWholeNum;

    public NumCounter(int num, int sum, boolean isWholeNum) {
        this.num = num;
        this.sum = sum;
        this.isWholeNum = isWholeNum;
    }

    public NumCounter accumulate(Character c) {
        System.out.println(Thread.currentThread().getName()+"handle "+ c);
        if (Character.isDigit(c)) {
            return isWholeNum ? new NumCounter(Integer.parseInt("" + c), sum, false) : new NumCounter(Integer.parseInt("" + num + c), sum, false);
        } else {
            return new NumCounter(0, sum + num, true);
        }
    }

    public NumCounter combine(NumCounter numCounter) {
        System.out.println("合并结果：" + this.getSum()+ " "+numCounter.getSum());
        return new NumCounter(0, this.getSum() + numCounter.getSum(), numCounter.isWholeNum);
    }

    public int getSum() {
        return sum + num;
    }

    public static void main(String[] args) {
        int a= 12+3+21+34+45+3+34+8+3+1+213+55;
        System.out.println(a);
        String arr = "12%3 21sdas s34d dfsdz45   R3 jo34 sjkf8 3$1P 213ikflsd fdg55 kfd";
//        12+3+21+34+45+3+34+8+3+1+213+55
        Stream<Character> stream = IntStream.range(0, arr.length()).mapToObj(arr::charAt);
        //串行
//        System.out.println("ordered total: " + countNum(stream));

        //并行
//        System.out.println("ordered total: " + countNum(stream.parallel()));

    }

    private static int countNum(Stream<Character> stream){
        NumCounter numCounter = stream.reduce(new NumCounter(0, 0, false), NumCounter::accumulate, NumCounter::combine);
        return numCounter.getSum();
    }
}
